package com.alipay.rebate.shop.utils;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.pojo.weixin.WeiXinAccessTokenRsp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WeiXinUtil {

    private final static String APP_ID = "wx1e888c66073cad17";
    private final static String APP_SECRET = "e832f9db1295f5c59fc08ba3f45212c5";
    static ObjectMapper objectMapper = new ObjectMapper();
    private static Logger logger = LoggerFactory.getLogger(WeiXinUtil.class);

    //获取access_token
    public static WeiXinAccessTokenRsp getAccessToken() {
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            Map<String, String> map = new HashMap<>();
            map.put("grant_type", "client_credential");
            map.put("appid", "wx1e888c66073cad17");
            map.put("secret", "e832f9db1295f5c59fc08ba3f45212c5");
            String sendGet = HttpUtils.sendGet(url, map);
            WeiXinAccessTokenRsp weiXinAccessTokenRsp = objectMapper.readValue(sendGet, WeiXinAccessTokenRsp.class);
            logger.debug("weiXinAccessTokenRsp is : {}", weiXinAccessTokenRsp);
//        Object readValue = objectMapper.readValue(sendGet, Object.class);
//        logger.debug("readValue is : {}",readValue);
            return weiXinAccessTokenRsp;
        }catch (IOException e){
            logger.debug("getAccessToken exception is : {}"+e);
            throw new BusinessException("公众号appId无效", StatusCode.PARAMETER_CHECK_ERROR);
        }
    }

    // 获取用户微信基本信息
    public static Object getWeiXinUserInfo(String openId) throws IOException {
        WeiXinAccessTokenRsp accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info";
        Map<String, String> map = new HashMap<>();
        map.put("access_token", accessToken.getAccess_token());
        map.put("openid", openId);
        map.put("lang", "zh_CN");
        String sendGet = HttpUtils.sendGet(url, map);
        Object readValue = objectMapper.readValue(sendGet, Object.class);
        logger.debug("readValue is : {}", readValue);
        return readValue;
    }

}
